package pl.edu.agh.gp;

import org.apache.log4j.Logger;
import org.jgap.event.GeneticEvent;
import org.jgap.event.GeneticEventListener;
import org.jgap.gp.impl.GPGenotype;
import pl.edu.agh.gp.fitness.OverBHFitnessFunction;

public class GpPopulationListener implements GeneticEventListener {
    private Logger logger = Logger.getLogger(GpPopulationListener.class);
    private final double FINANCIAL_MIN = -1000000;   // 1 mln
    private final OverBHFitnessFunction fitnessFunc;
    private int evolutionNo = 0;
    private double bestFitness = FINANCIAL_MIN;

    public GpPopulationListener(OverBHFitnessFunction fitnessFunc) {
        this.fitnessFunc = fitnessFunc;
    }

    @Override
    public void geneticEventFired(GeneticEvent geneticEvent) {
        logger.trace("Got gp event.");

        Object value = geneticEvent.getSource();

        if(value instanceof GPGenotype){
            GPGenotype genotype = (GPGenotype) value;
            double fitness = genotype.getTotalFitness();
            if(fitness == 0.0){
                fitness = fitnessFunc.getBestFitness();
            }
            if(fitness > bestFitness){
                bestFitness = fitness;
                logger.debug("Current best fitness: " + bestFitness + " with program: " + fitnessFunc.getBestProgram().toStringNorm(0));
            }
            logger.debug("Evolution: " + evolutionNo++);
        }
    }
}
